/**
 * 17. 电话号码的字母组合
 * https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
 */

const digitMap = {
  2: [97, 98, 99],
  3: [100, 101, 102],
  4: [103, 104, 105],
  5: [106, 107, 108],
  6: [109, 110, 111],
  7: [112, 113, 114, 115],
  8: [116, 117, 118],
  9: [119, 120, 121, 122],
};

/**
 * @description 获取字串的组合情况
 * @param {string[]} result
 * @param {string} digits
 * @param {number} index
 * @param {Uint8Array} cache
 * @param {DataView} view
 */
function childCombinations(result, digits, index, cache, view) {
  const end = index === digits.length - 1;
  const chars = digitMap[digits.charAt(index)];
  chars.forEach((char) => {
    view.setUint8(index, char);
    if (end) {
      result.push(String.fromCharCode.apply(null, cache));
    } else {
      childCombinations(result, digits, index + 1, cache, view);
    }
  });
}

/**
 * @param {string} digits
 * @return {string[]}
 */
function letterCombinations(digits) {
  const result = [];
  if (!digits) return result;
  const { length } = digits;
  const cache = new Uint8Array(length);
  const view = new DataView(cache.buffer);
  childCombinations(result, digits, 0, cache, view);
  return result;
}

console.log(letterCombinations('23'));
console.log(letterCombinations(''));
console.log(letterCombinations('2'));
